﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NerdDinner.Web.Models.Data;
using NerdDinner.Web.Models.Repository;

namespace NerdDinner.Tests.Mocks
{
    public class MockDinnerRepository : IDinnerRepository
    {
        private List<Dinner> _dinnerList;

        public MockDinnerRepository() : this(new List<Dinner>()) { }

        public MockDinnerRepository(List<Dinner> dinnerList)
        {
            if (dinnerList.Count == 0)
                dinnerList = CreateTestDinners();
            _dinnerList = dinnerList;
        }

        private List<Dinner> CreateTestDinners()
        {
            List<Dinner> dinners = new List<Dinner>();
            for (int i = 0; i < 100; i++)
            {
                Dinner sampleDinner = new Dinner()
                {
                    DinnerId = i,
                    Title = "Sample Dinner",
                    HostedBy = "SomeUser",
                    Address = "Some Address",
                    Country = "USA",
                    ContactPhone = "425-555-1212",
                    Description = "Some description",
                    EventDate = DateTime.Now.AddDays(i),
                    Latitude = 99,
                    Longitude = -99
                };

                dinners.Add(sampleDinner);
            }
            return dinners;
        }

        #region IDinnerRepository Members

        public IQueryable<Dinner> FindAllDinners()
        {
            return _dinnerList.AsQueryable();
        }

        public IQueryable<Dinner> FindByLocation(float latitude, float longitude, int distance)
        {
            return (from dinner in _dinnerList
                    where dinner.Latitude == latitude && dinner.Longitude == longitude
                    select dinner).AsQueryable();
        }

        public IQueryable<NerdDinner.Web.Models.Data.Dinner> FindUpcomingDinners()
        {
            return (from dinner in _dinnerList
                    where dinner.EventDate > DateTime.Now
                    orderby dinner.EventDate
                    select dinner).AsQueryable();
        }

        public Dinner GetDinner(int id)
        {
            return _dinnerList.SingleOrDefault(d => d.DinnerId == id);
        }

        public void Add(Dinner dinner)
        {
            _dinnerList.Add(dinner);
        }

        public void Delete(Dinner dinner)
        {
            _dinnerList.Remove(dinner);
        }

        public void Save()
        {
            foreach (Dinner dinner in _dinnerList)
            {
                if (!dinner.IsValid)
                    throw new ApplicationException("Rule violations");
            }
        }

        #endregion
    }
}
